package bar.dark.lee.setting.sms;

import java.math.BigDecimal;

import android.app.Activity;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import bar.dark.lee.BDConstents;
import bar.dark.lee.IntroPasswordActivity;
import bar.dark.lee.R;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.BalanceQuery;

public class SmsInputService extends IntentService {

	//private Bundle bundle;
	private String smsAddress;
	private String smsBody;
	
	private DBSQLite sql;
	private Context context;
//	private Intent intent;
	private String messageCardName;
	private int parserNumber = -1;
	private String linkCardName;
	private String linkCardType;
	
	//private int flag = 1;	// 번호와 내용이 1번컬럼인지 2번컬럼인지(1번:dispalyoriginal... 2번:그냥)
	
	private int cardCount;
	
	private int smsType = -1;
	
	private NotificationManager nm = null;
	
	public SmsInputService() {
		super("SmsInputService");
	}
	
	public SmsInputService(String name) {
		super(name);
	}

	@Override
	protected void onHandleIntent(Intent paramIntent) {
		
		//this.bundle = paramIntent.getExtras();
		smsAddress = paramIntent.getStringExtra("sms_address");
		smsBody = paramIntent.getStringExtra("sms_body");
		
		context = getApplicationContext();
		
		Parser parser2 = null;
		try {
			parser2 = new Parser(smsBody);
		} catch (Exception e)
		{
			return;
		} finally
		{
			if (parser2 == null)
			{
				return;
			}
		}
		
		InputData data = new InputData();
		data = parser2.messageParsing();
		smsType = parser2.getSmsType();
		
		if (smsType == -1 || smsType == BDConstents.HALBU_SMS)
		{
			return;
		}
		
		if (data == null || !parser2.getAvailable()) 
		{
			return;
		}
		
		messageCardName = data.getName();
		//Log.e("messageCardName", messageCardName);
		
		if ( !getPaySMSData(context) )
		{
			return;
		}
//			Log.e("aaa", "aaa");
//			if ( !getPaySMSData(context, 2) )
//			{
//				return;
//			}
//			else
//			{
//				flag = 2;
//			}
//		}
//		else
//		{
//			flag = 1;
//		}
		
//		Log.e("3", "3");
		
//		Log.e("parserNumber", parserNumber+"");
		if (parserNumber == -1)
		{
//			Log.e("xxx", "xxx");
			return;
		}
		
		String date = data.getDate();
		String money = data.getMoney();
		//int parserNumber = Integer.parseInt(mArrayPaySMSData.get(i).getParser());
		String memo = "";
		
		switch (parserNumber) {
			case 1:
				memo = data.getMemo1();
			break;
			case 2:
				memo = data.getMemo2();
			break;
			case 3:
				memo = data.getMemo3();
			break;
			case 4:
				memo = data.getMemo4();
			break;
			default:
			break;
		}
		
//		Log.e("4", "4");
		
		SharedPreferences pref = context.getSharedPreferences("pref", Activity.MODE_PRIVATE);
		int question = pref.getInt("smsRadioGroup", 1);
		question = pref.getInt("smsRadioGroup", 1);
		switch (question) {
			case 1:
				// 허용안함
			break;
			case 2:
				// 허용
				
				//abortBroadcast();
				
				BigDecimal tempMoney;
				
				try {
					
					tempMoney = new BigDecimal(money);
					
				} catch (Exception e)
				{
					return;
				}
				
				SMSInsertDB insertDB = new SMSInsertDB();
				
				boolean cardEmptyflag = false;
				
				// 신용카드
				if (linkCardType.equalsIgnoreCase("3")) 
				{
					try
					{
						sql.beginTansaction(context);
						
						cardEmptyflag = insertDB.creditOutInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
						
						// 잔액을 입력 하기 전에 타입과 이름이 없으면 익셉션 발생
						if (linkCardType.equals("") || linkCardName.equals(""))
						{
							throw new Exception();
						}
						
						// 잔액을 입력한다.
						BalanceQuery balace = new BalanceQuery(context);
						balace.setBalance(BDConstents.CREDIT_TYPE, linkCardName);
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						//Toast.makeText(context, "꿀꿀이 가계부 입력 실패! 개발자에게 문의하세요!", Toast.LENGTH_SHORT).show();
					} finally {
						try 
						{
							sql.endTransaction(context);
						} catch (Exception e) 
						{
						}
					}
				} 
				// 체크카드
				else if (linkCardType.equalsIgnoreCase("4")) 
				{
					try
					{
						sql.beginTansaction(context);
						
						// 지출인지 수입인지 플래그
						int flag = 0;
						
						if (smsType == BDConstents.IN_SMS)
						{
							cardEmptyflag = insertDB.checkInInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
							flag = 1;
						}
						else if (smsType == BDConstents.OUT_SMS)
						{
							cardEmptyflag = insertDB.checkOutInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
							flag = 0;
						}
						else if (smsType == BDConstents.IN_ATM_SMS)
						{
							cardEmptyflag = insertDB.checkInAtmInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
							flag = 1;
						}
						else if (smsType == BDConstents.OUT_ATM_SMS)
						{
							cardEmptyflag = insertDB.checkOutAtmInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
							flag = 0;
						}
						
						// 잔액을 입력 하기 전에 타입과 이름이 없으면 익셉션 발생
						if (linkCardType.equals("") || linkCardName.equals(""))
						{
							throw new Exception();
						}
						
						// 잔액을 입력한다.
						BalanceQuery balace = new BalanceQuery(context);
						balace.setBalance(BDConstents.CHECK_TYPE, linkCardName);
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						//Toast.makeText(context, "꿀꿀이 가계부 입력 실패! 개발자에게 문의하세요!", Toast.LENGTH_SHORT).show();
					} finally {
						try 
						{
							sql.endTransaction(context);
						} catch (Exception e) 
						{
						}
					}
				}
				// 통장
				else if (linkCardType.equalsIgnoreCase("1")) 
				{
					try
					{
						sql.beginTansaction(context);
						
						// 지출, 수입 플래그
						int flag = 0;
						
						if (smsType == BDConstents.IN_SMS)
						{
							cardEmptyflag = insertDB.bankInInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
							flag = 1;
						}
						else if (smsType == BDConstents.OUT_SMS)
						{
							cardEmptyflag = insertDB.bankOutInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
							flag = 0;
						}
						else if (smsType == BDConstents.IN_ATM_SMS)
						{
							cardEmptyflag = insertDB.bankInAtmInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
							flag = 1;
						}
						else if (smsType == BDConstents.OUT_ATM_SMS)
						{
							cardEmptyflag = insertDB.bankOutAtmInsert(context, sql, linkCardType, linkCardName, date, tempMoney, memo, "");
							flag = 0;
						}
						
						// 잔액을 입력 하기 전에 타입과 이름이 없으면 익셉션 발생
						if (linkCardType.equals("") || linkCardName.equals(""))
						{
							throw new Exception();
						}
						
						// 잔액을 입력한다.
						BalanceQuery balace = new BalanceQuery(context);
						balace.setBalance(BDConstents.BANK_TYPE, linkCardName);
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						//Toast.makeText(context, "꿀꿀이 가계부 입력 실패! 개발자에게 문의하세요!", Toast.LENGTH_SHORT).show();
					} finally {
						try 
						{
							sql.endTransaction(context);
						} catch (Exception e) 
						{
						}
					}
				}
				
				if (cardEmptyflag) 
				{
					//BDUtil.showToast(context, "꿀꿀이 가계부에 내역을 입력했습니다");
					
					//int notiId = 1008;
					 
					int smsNoti = pref.getInt(BDConstents.SMS_NOTI_SETTING, 0);
					if (smsNoti == 0)
					{
						nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
						
						String notifiedTitle = "꿀꿀이 가계부 내역 입력";
						String typeString = "";
						switch (smsType)
						{
							case BDConstents.IN_SMS:
								typeString = "입금";
								break;
							case BDConstents.OUT_SMS:
								typeString = "지출";
								break;
							case BDConstents.IN_ATM_SMS:
								typeString = "현금입금";
								break;
							case BDConstents.OUT_ATM_SMS:
								typeString = "현금출금";
								break;
							default:
								break;
						}
					
						String notifiedMessage = data.getName() + " / " + data.getMoney() + "원(" + typeString + ") / " + memo;
						
						Notification noti = new Notification(R.drawable.icon, "꿀꿀이 가계부에 내역을 입력했습니다.", System.currentTimeMillis());
						
						Intent intent2 = new Intent(context.getApplicationContext(), IntroPasswordActivity.class);
					    intent2.putExtra("notifiedTitle", notifiedTitle);
					    intent2.putExtra("notifiedMessage", notifiedMessage);
					    PendingIntent pIntent = PendingIntent.getActivity(context.getApplicationContext(), (int)System.currentTimeMillis(), intent2, Intent.FLAG_ACTIVITY_NEW_TASK);
					    noti.setLatestEventInfo(context.getApplicationContext(),  notifiedTitle, notifiedMessage, pIntent);

					    // noti를 클릭 했을 경우 자동으로 noti Icon 제거
					    noti.flags = noti.flags | noti.FLAG_AUTO_CANCEL;
					    
					    // notify
					    //noti.number += 1;
					   
					    nm.notify((int)System.currentTimeMillis(), noti);
					}
					else 
					{
						//BDUtil.showToast(context, "꿀꿀이 가계부에 내역을 입력했습니다.");
					}
				    
				}
			break;
			case 3:
				// 질문
				
				//abortBroadcast();
				
				String query = "";
				cardCount = 0;
				String name = "";
				
				if (linkCardType.equalsIgnoreCase("4"))
				{
					query = "SELECT * FROM check_card WHERE name = '" + BDUtil.getApostrophe(linkCardName) + "';";
					name = "체크카드";
				}
				else if (linkCardType.equalsIgnoreCase("3"))
				{
					query = "SELECT * FROM credit_card WHERE name = '" + BDUtil.getApostrophe(linkCardName) + "';";
					name = "신용카드";
				}
				else if (linkCardType.equalsIgnoreCase("1"))
				{
					query = "SELECT * FROM bankbook WHERE name = '" + BDUtil.getApostrophe(linkCardName) + "';";
					name = "통장";
				}
				
				try 
				{
					sql.selectMapTile(context, query, new ParseSelectData() 
					{
						@Override
						public void resultData(Cursor c) 
						{
							cardCount = c.getCount();
						}
					});
				} catch (Exception e)
				{
					
				} finally 
				{
					if (cardCount < 1) 
					{
						//BDUtil.showToast(context, name + "가(이) 없어서 입력에 실패했습니다.");
						return;
					}
				}
				
				Intent intent2 = new Intent(context, SMSDialogActivity.class);
				intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent2.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
				
//				if (flag == 1)
//				{
					intent2.putExtra("address", smsAddress);
//				}
//				else if (flag == 2)
//				{
//					intent2.putExtra("address", address2);
//				}
				intent2.putExtra("name", messageCardName);
				intent2.putExtra("date", date);
				intent2.putExtra("money", money);
				intent2.putExtra("memo", memo);
				intent2.putExtra("linkCardType", linkCardType);
				intent2.putExtra("linkCardName", linkCardName);
				intent2.putExtra("smsType", smsType);
				context.startActivity(intent2);					
			break;
			default:
			break;
		}
	}
	
	private boolean returnFlag = false;
	/**
	 * 결제문자정보 데이터 가져온다
	 */
	private boolean getPaySMSData(Context context) {
		
		sql = DBSQLite.getInstance(context);
		
		String query = "";
		
		if (smsAddress != null || smsAddress.length() == 0)
		{
			query = "SELECT messagecardname, linkcardname, linkcardtype, parser FROM sms where address = '" + 
						BDUtil.getApostrophe(smsAddress) + "' and messagecardname = '" + 
						BDUtil.getApostrophe(messageCardName) + "';";
		}
		else
		{
			returnFlag = false;
			return returnFlag;
		}
		
		try {
			sql.selectMapTile(context, query, new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					//Log.e("1", "resultData");
					int count = c.getCount();
					c.moveToFirst();
					
					if (count != 0)
					{
						//int addressIndex = c.getColumnIndex("address");
						//int nameIndex = c.getColumnIndex("name");
						int messageCardNameIndex = c.getColumnIndex("messagecardname");
						int parserIndex = c.getColumnIndex("parser");
						int linkCardNameIndex = c.getColumnIndex("linkcardname");
						int linkCardTypeIndex = c.getColumnIndex("linkcardtype");
						
						for (int i = 0; i < count; i++)
						{
							if (messageCardName.equals(c.getString(messageCardNameIndex))) 
							{
								parserNumber = Integer.parseInt(c.getString(parserIndex));
								linkCardName = c.getString(linkCardNameIndex);
								linkCardType = c.getString(linkCardTypeIndex);
//								Log.e(logTag, "messageCardName : "+messageCardName);
//								Log.e(logTag, "parser : "+parserNumber);
//								Log.e(logTag, "linkCardName : "+linkCardName);
//								Log.e(logTag, "linkCardType : "+linkCardType);
							}
							
							c.moveToNext();
						}
						
						returnFlag = true;
					}
					else
					{
						returnFlag = false;			
					}
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
			returnFlag = false;
			
			return returnFlag;
		}
		
		return returnFlag;
	}

}
